package edu.utdallas_elearn_calendar.utdallas_elearn_calendar_app;

import java.util.Calendar;

import edu.utdallas_elearn_calendar.utdallas_elearn_calendar_db.CalDbAdapter;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;

public class event_edit extends Activity {
	private static final int DATE_MENU = 1; 
	private static final int TIME_MENU = 2;
	private EditText mEventNameText;
	private Spinner mEventClassIdSpin;
	private Spinner mEventTypeIdSpin;	
	private EditText mEventDueDateText;
	private EditText mEventTimeText;
	private EditText mEventReminderText;
	private Spinner mEventRecurranceSpin;
	private Long mRowId;
	private CalDbAdapter mDbHelper;
	
	//The calendar object to store the date.
	private Calendar day;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		mDbHelper = new CalDbAdapter(this);
		mDbHelper.open();
        setContentView(R.layout.event_edit);
		  
        mEventNameText = (EditText) findViewById(R.id.event_edit_name);
        mEventClassIdSpin = (Spinner) findViewById(R.id.event_edit_class);
        mEventTypeIdSpin = (Spinner) findViewById(R.id.event_edit_event_type);		
        mEventDueDateText = (EditText) findViewById(R.id.event_edit_due_date);
        mEventTimeText = (EditText) findViewById(R.id.event_edit_due_time);
        mEventReminderText = (EditText) findViewById(R.id.event_edit_minutes);
        mEventRecurranceSpin = (Spinner) findViewById(R.id.event_edit_recurrance);

		Button saveButton = (Button) findViewById(R.id.event_edit_button);
		mRowId = null;
		Bundle extras = getIntent().getExtras();
		mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
				.getSerializable(CalDbAdapter.ROW_ID);
		
		if (extras != null) {
			mRowId = extras.getLong(CalDbAdapter.ROW_ID);
		}
		
		//Toast.makeText(this, "The id number of this event record is " + mRowId + ".", Toast.LENGTH_LONG).show();
		
		populateFields();
		
		day = Calendar.getInstance();
	
		mEventDueDateText.setClickable(true);
		mEventDueDateText.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				showDialog(DATE_MENU);				
			}
		});
		
		mEventTimeText.setClickable(true);
		mEventTimeText.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				showDialog(TIME_MENU);				
			}
		});
		
		saveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setResult(RESULT_OK);
				finish();
			}
		});

    }
    
	private void populateFields() {
		int index = 0;
		long classId = 1;
		long eventTypeId = 1;
		String due_date = "";
		String year = "";
		
		if (mRowId != null && mRowId != 0) {
			Cursor currentRow = mDbHelper.getViewEvent(mRowId);
			startManagingCursor(currentRow);
			
			mEventNameText.setText(currentRow.getString(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.EVENT_NAME)));
			
			classId = currentRow.getLong(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.CLASS_ID));
			
			eventTypeId = currentRow.getLong(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.EVENT_TYPE_ID));			
			
			due_date = currentRow.getString(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE)).substring(0, 
							currentRow.getString(currentRow
									.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE)).indexOf(" "));
			
			// put due date in a human readable format
			year = due_date.substring(0, due_date.indexOf("-"));
			due_date = due_date.substring(due_date.indexOf("-")+1, due_date.length());			
			due_date = due_date + "-" + year;

			mEventDueDateText.setText(due_date);			
			
			mEventTimeText.setText(currentRow.getString(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE)).substring(
							currentRow.getString(currentRow
									.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE)).indexOf(" ")+1,
									currentRow.getString(currentRow
											.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE)).length()));
			
			mEventReminderText.setText(currentRow.getString(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.REMINDER_MINUTES)));
			
			mEventRecurranceSpin.setSelection(currentRow.getInt(currentRow
					.getColumnIndexOrThrow(CalDbAdapter.EVENT_RECURRENCE)));
			
			currentRow.close();
		}
		
		index = populateClassSpin(classId);
		mEventClassIdSpin.setSelection(index);
		
		index = populateEventTypeSpin(eventTypeId);
		mEventTypeIdSpin.setSelection(index);				
	}
	
	private int populateClassSpin(long classId) {
		Cursor currentRow = mDbHelper.getAllClasses();
		
		startManagingCursor(currentRow);
				
		// create an array to specify which fields we want to display
		String[] from = new String[]{CalDbAdapter.CLASS_TITLE};

		// create an array of the display item we want to bind our data to
		int[] to = new int[]{android.R.id.text1};
		
		// create simple cursor adapter
		SimpleCursorAdapter adapter =
		  new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, currentRow, from, to );
		
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		
		// get reference to our spinner
		Spinner s = (Spinner) findViewById( R.id.event_edit_class );
		s.setAdapter(adapter);
		
		int index = 0;
		int returnVal = 0;
		
		currentRow.moveToFirst();
		
		if(currentRow.getCount() > 0)
		{			
			do
			{
				if (classId == currentRow.getLong(currentRow.getColumnIndexOrThrow(CalDbAdapter.ROW_ID))) {
					returnVal = index;
				}
				index++;
			}
			while(currentRow.moveToNext());
		}
		else
		{
			Log.i("DATABASE", "getAllClasses: no classes found");
		}
		
		return returnVal;
		
	}
	
	private int populateEventTypeSpin(long eventTypeId) {
		Cursor currentRow = mDbHelper.getAllEventType();
		
		startManagingCursor(currentRow);
				
		// create an array to specify which fields we want to display
		String[] from = new String[]{CalDbAdapter.EVENT_TYPE};

		// create an array of the display item we want to bind our data to
		int[] to = new int[]{android.R.id.text1};
		
		// create simple cursor adapter
		SimpleCursorAdapter adapter =
		  new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, currentRow, from, to );
		
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		
		// get reference to our spinner
		Spinner s = (Spinner) findViewById( R.id.event_edit_event_type );
		s.setAdapter(adapter);
		
		int index = 0;
		int returnVal = 0;
		
		currentRow.moveToFirst();
		
		if(currentRow.getCount() > 0)
		{			
			do
			{
				if (eventTypeId == currentRow.getLong(currentRow.getColumnIndexOrThrow(CalDbAdapter.ROW_ID))) {
					returnVal = index;
				}
				index++;
			}
			while(currentRow.moveToNext());
		}
		else
		{
			Log.i("DATABASE", "getAllEventTypes: no event types found");
		}
		
		return returnVal;
		
	}
	
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(CalDbAdapter.ROW_ID, mRowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
//		mDbHelper.close();		
	}

	@Override
	protected void onResume() {
		super.onResume();
//		mDbHelper.open();
		populateFields();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mDbHelper != null) {
			mDbHelper.close();
		}
	}
	
	private void saveState() {	
		String name = mEventNameText.getText().toString();
		long class_id = mEventClassIdSpin.getSelectedItemId();
		long event_type_id = mEventTypeIdSpin.getSelectedItemId();
		String due_date = mEventDueDateText.getText().toString();
		String time = mEventTimeText.getText().toString();
		
		// put the date in sqlite date format
		due_date = formatSqlDate(due_date, time);
		
		String minutes = mEventReminderText.getText().toString();
		long recurring_type = mEventRecurranceSpin.getSelectedItemId();
		int minutes_prior = 0;
		
		if (minutes.length() > 0) {
			minutes_prior = Integer.parseInt(minutes);
		}

		// Insert a new or update an existing class
		if (mRowId == null || mRowId == 0) {
			
			long id = mDbHelper.insertEvent(class_id, event_type_id, name, due_date, recurring_type);
			
			if (id > 0) {
				mRowId = id;				
				
				if (minutes_prior > 0) {
					id = mDbHelper.insertReminder(mRowId, minutes_prior);
				}
			}
		} else {

			mDbHelper.updateEvent(mRowId, class_id, event_type_id, name, due_date, recurring_type);
			mDbHelper.updateReminder(mRowId, class_id, minutes_prior);
		}
		
		mDbHelper.close();
		finish();
	}
	
	/*
	*In this function the dialog is created. We use a switch to determine which dialog is being called.
	*We add a switch and only add the ID 10 which we added in the previous function. With this function
	*the dialog is created and visible on the screen.
	*/
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_MENU:
			return new DatePickerDialog(this, mDateSetListener, day.get(Calendar.YEAR), day.get(Calendar.MONTH), day.get(Calendar.DAY_OF_MONTH));
		case TIME_MENU:
			return new TimePickerDialog(this, mTimeSetListener, day.get(Calendar.HOUR_OF_DAY), day.get(Calendar.MINUTE), true);
		}

		return null;	    
	}
	
    /*
     * This object is used to set the day and do things after the day has
     * been selected.
     */	
    private final DatePickerDialog.OnDateSetListener mDateSetListener =
    	new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
	            day.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	            day.set(Calendar.MONTH, monthOfYear);
	            day.set(Calendar.YEAR, year);
               
	       		String sMonth = "" + (monthOfYear+1);
	       		if(sMonth.length()<2) {sMonth = "0" + sMonth;}	
	    		String sDate = "" + dayOfMonth;
	    		if(sDate.length()<2) {sDate = "0" + sDate;}	
               
	    		mEventDueDateText.setText(sMonth + "-" + sDate + "-" + year);
            }
     };
     
     /*
      * This object is used to set the time for the text field
      */
     private final TimePickerDialog.OnTimeSetListener mTimeSetListener =
    	new TimePickerDialog.OnTimeSetListener() {
             public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
            	 day.set(Calendar.HOUR_OF_DAY, hourOfDay);
            	 day.set(Calendar.MINUTE, minute);
            	 
            	 String sHour = "" + hourOfDay;
 	       		 if(sHour.length()<2) {sHour = "0" + sHour;}	
 	    		 String sMinute = "" + minute;
 	    		 if(sMinute.length()<2) {sMinute = "0" + sMinute;}	
            	 
                 mEventTimeText.setText(sHour + ":" + sMinute);
             }
     };
      
     private String formatSqlDate(String due_date, String time) {
		String month = "";
		String date = "";
		String year = "";
		String hour = "";
		String minutes = "";
		
		if (due_date.length() > 0) {		
			month = due_date.substring(0, due_date.indexOf("-"));
			if(month.length()<2) {month = "0" + month;}		
			due_date = due_date.substring(due_date.indexOf("-")+1, due_date.length());	
			
			date = due_date.substring(0, due_date.indexOf("-"));
			if (date.length()<2) {date = "0" + date;}		
			due_date = due_date.substring(due_date.indexOf("-")+1, due_date.length());
			
			year = due_date.substring(0, due_date.length());
		}
		
		if (time.length() > 0) {
			hour = time.substring(0, time.indexOf(":"));
			if (hour.length()<2) {hour = "0" + hour;}
			
			minutes = time.substring(time.indexOf(":")+1, time.length());
			if (minutes.length()<2) {minutes = "0" + minutes;}
		}
		
		return year + "-" + month + "-" + date + " " + hour + ":" + minutes;
	 }
}	